package com.lepu.app.fun.my.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragment;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.core.lib.widget.GoogleRefreshLayout.OnScrollListener;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.grow.GrowHotPhotoDetailActivity;
import com.lepu.app.fun.grow.bean.HotPhoto;
import com.lepu.app.fun.my.MyPubContentActivity;
import com.lepu.app.fun.my.adapter.AdapterPubContentHotPhoto;
import com.lepu.app.usercenter.UserOtherInfoActivity;
import com.lepu.app.usercenter.bean.LoginInfo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class FragmentMyHotPhoto extends BaseFragment implements AsyncRequest, OnRefreshListener,
OnLoadListener,OnScrollListener{

	private static FragmentMyHotPhoto mFragmentInstance = null;
	private View mMainView = null;
	private boolean mInitDataSuccess = false;//是否加载完数据
	
	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	// 我的主题列表，可以删除主题
	private static final String REQUEST_DELETE_TOPIC = "request_delete_topic";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;

	// ========================================================================
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private AdapterPubContentHotPhoto mDataAdapter = null;
	private ArrayList<HotPhoto> mDataArrayList = null;
	private int mCurrentPage = 1;

	private String mCurrentDate = null;

	private int mCurrentSelectIndex = 0;
	
	public boolean mNeedRefresh = false;
	
	public String mFromContext = "";
	public String mTargetUserID = "";
	
	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMainView = LayoutInflater.from(getActivity()).inflate(
				R.layout.my_pub_content_fragment_hotphoto,null,
				false);
		init();
		mFragmentInstance = this;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
		mFragmentInstance = null;
	}
	
	public static FragmentMyHotPhoto getInstance()
	{
		return mFragmentInstance;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				// 第一次进入页面获取数据
				showFirstLoadDataLayout(true);
				request(false);
			}
		}
	}
	
	/*
	 * 初始化ui控件，不要初始化数据！！！！
	 * 
	 * 初始化控件，需要用mMainView.findViewById
	 * 不能使用findViewById，否则程序会闪退的
	 */
	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("ResourceAsColor")
	private void init() {

		mDataListView = (ListView) mMainView.findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) mMainView.findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setOnScrollListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);

		Bundle data = getArguments();
		mFromContext = data.getString("fromContext");
		mTargetUserID = data.getString("targetUserID");
		
		mDataListView.setOnItemClickListener(mOnItemClickListener);

	}
	
	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				if(mDataArrayList == null || mDataArrayList.size() == 0)
				{
					noDataLayout.setVisibility(View.VISIBLE);
				}
			}else{
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}
	
	private void showFirstLoadDataLayout(boolean isShow)
	{
		LinearLayout firstLoadDataLayout = (LinearLayout) mMainView.findViewById(R.id.firstLoadDataLayout);
		if(firstLoadDataLayout != null)
		{
			if(isShow)
			{
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
			}else{
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	public void deleteItem(final int index) {

		MyDialog dialog = new MyDialog(getActivity())
				.setMessage("您确认要删除这条内容吗?")
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						mCurrentSelectIndex = index;
						
//						HotPhoto item = mDataArrayList.get(index);
//						requestDeleteTopic(item.TopicID);
					}
				})
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}

	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			mCurrentDate = DateUtilBase.stringFromDate(new Date(),
					DateUtilBase.DATE_ALL_ALL);
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		String url = Setting.getMyShareAlbumListUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("TargetUserID", mTargetUserID);
			params.put("RefreshTime", mCurrentDate);
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true);

	}

	public void requestDeleteTopic(String topicId) {
		String url = Setting.getDeleteTopicUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("TopicIDList", topicId);
		} catch (Exception e) {
		}
		map.put("ht", params);

		MyPubContentActivity.getInstance().showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, REQUEST_DELETE_TOPIC,
				false);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				if(getActivity() == null)
				{
					return;
				}

				@SuppressWarnings("unchecked")
				ArrayList<HotPhoto> dataList = (ArrayList<HotPhoto>) msg.obj;
				if (dataList != null && dataList.size() > 0) {

					mInitDataSuccess = true;
					mDataArrayList = dataList;
					
					showHideNoDataLayout(false);
				} else {
					//UIHelper.showToast(getActivity(),R.string.no_data);
					
					if(mDataArrayList != null && mDataArrayList.size() > 0){
						mDataArrayList.clear();
					}
					
					showHideNoDataLayout(true);
				}
				
				if (mDataArrayList == null) {
					mDataArrayList = new ArrayList<HotPhoto>();
				}
				
				ImageView tempImageView = new ImageView(getActivity());
				mDataListView.addHeaderView(tempImageView);
				
				mDataAdapter = new AdapterPubContentHotPhoto(
						getActivity(), mDataArrayList);
				mDataListView.setAdapter(mDataAdapter);
				
				mDataListView.removeHeaderView(tempImageView);

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				showFirstLoadDataLayout(false);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				showFirstLoadDataLayout(false);
				
				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<HotPhoto> dataMoreList = (ArrayList<HotPhoto>) msg.obj;
				if (dataMoreList != null && dataMoreList.size() > 0) {
					mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(getActivity(),
							R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	public void deleteIndex() {
		mDataArrayList.remove(mCurrentSelectIndex);
		mDataAdapter.notifyDataSetChanged();
	}

	private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			mCurrentSelectIndex = position;

			HotPhoto item = mDataArrayList.get(position);
			
			Intent intent = new Intent(getActivity(),
					GrowHotPhotoDetailActivity.class);
			intent.putExtra("HotPhotoId", item.AlbumID);
			((BaseFragmentActivity)getActivity()).startActivity(intent, true);
		}
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			// 解析json data
			ArrayList<HotPhoto> dataArraylist = HotPhoto
					.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			// 解析json data more
			ArrayList<HotPhoto> dataMoreArraylist = HotPhoto
					.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					HotPhoto item = dataMoreArraylist.get(i);
					mDataArrayList.add(item);
				}
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DELETE_TOPIC)) {
			// main thread
			MyPubContentActivity.getInstance().hideProgressDialog();

			deleteIndex();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} else if (object.equals(REQUEST_DELETE_TOPIC)) {
			// main thread

			MyPubContentActivity.getInstance().hideProgressDialog();
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
		if(mFromContext.equals("UserOtherInfoActivity")){

//			if(UserOtherInfoActivity.getInstance() == null)
//			{
//				return;
//			}
//			if(firstVisibleItem > 1 && UserOtherInfoActivity.getInstance().mCurrentTab == 1){
//				UserOtherInfoActivity.getInstance().mTopLayout.setVisibility(View.GONE);
//			}else if(firstVisibleItem < 1 && UserOtherInfoActivity.getInstance().mCurrentTab == 1){
//				UserOtherInfoActivity.getInstance().mTopLayout.setVisibility(View.VISIBLE);
//			}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view,int scrollState) {
		if (scrollState == 0) {
			UniversalImageLoadTool.resume();
		} else {
			UniversalImageLoadTool.pause();
		}
	}
}
